import Store from 'store';

/**
 * 当校验出错时，重新校验
 * 用于数据修改后重新调用验证
 * @param {*} form
 * @param {*} fieldId
 */
export const recheckWhenError = (form, fieldId) => {
    if (!form || !fieldId) {
        return;
    }
    const { validateFields, getFieldError } = form;
    const error = getFieldError(fieldId);
    if (error?.length) {
        setTimeout(() => validateFields([fieldId], { force: true }));
    }
};

/**
 * @description:      存取设置页面的表单数据
 * @param {*} type    存取的方式
 * @param {*} key     存取的key
 * @param {*} value   存取的值
 * @return {*}
 */
export function FormDataStore({ type, key, value, action, id }) {
    const isCreate = action === 'create';
    switch (type) {
        case 'set': {
            // 先获取对应的storage
            let storage = Store.get(key) || {};
            value = isCreate ? { create: value } : { [id]: value };
            storage = { ...storage, ...value };
            Store.set(key, storage);
            break;
        }
        case 'get': {
            const storage = Store.get(key) || {};
            return storage[`${isCreate ? 'create' : id}`];
        }
        case 'remove': {
            const storage = Store.get(key) || {};
            delete storage[`${isCreate ? 'create' : id}`];
            Store.set(key, storage);
            break;
        }
        default:
            Store.remove(key);
    }
}

/**
 * @description: 判断是不是从其他路由跳转过来的
 */
export function currentUrlIsPrevUrl() {
    const pageTrack = Store.get('pageTrack');
    return pageTrack.url === pageTrack.lastPageUrl;
}

/**
 * @description: 清空缓存表单数据
 * @param {*} key
 * @param {*} action
 * @param {*} id
 * @return {*}
 */
export function removeFormStorage({ key, action, id }) {
    const isCreate = action === 'create';
    // 清空表单数据
    FormDataStore({ type: 'remove', key, action, id });
    // 清空最后一次保存的时间
    FormDataStore({ type: 'remove', key, id: `${isCreate ? 'create' : id}.saveTime` });
}
